﻿using QD.Tools;
using QD_Clients.Code;
using QD_Clients.Code.DbContent;
using QD_Clients.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity.Validation;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace QD_Clients
{
    public partial class Product : BaseForm
    {
        private PageState PageState = PageState.Browse;
        private Control[] readIgnoreControls;
        public Product()
        {
            InitializeComponent();
            #region 注册菜单
            base.ToolsBtnAdd = this.toolStripButton4;
            base.ToolsBtnModify = this.toolStripButton7;
            base.ToolsBtnUpdate = this.toolStripButton5;
            base.ToolsBtnDelete = this.toolStripButton3;
            base.ToolsBtnDetail = this.toolStripButton8;
            base.ToolsBtnClose = this.toolStripButton2;
            base.ToolsBtnPrevious = this.ts_prev;
            base.ToolsBtnNext = this.ts_next;
            #endregion

            this.grid_list.InitGrid();
            this.grid_list.RowTemplate.ContextMenuStrip = this.contextMenuStrip1;
        }

        private void Product_Load(object sender, EventArgs e)
        {
            if (!QDUserHelper.CurUser.IsManager)
            {
                MessageBox.Show("权限不足，请联系管理员！");
                this.Close();
            }

            readIgnoreControls = new Control[] { this.QfCode, this.QfName, this.CreateDate, this.cmbDeveloper, this.cmbLeader, this.cmbTester };
            //ControlHelper.SetChildReadonly(this.tabControl1.TabPages[0], true, readIgnoreControls);
            SetReadonly(true);

            QDResources db = new QDResources();
            DataTable dt_qduser = db.Query("select * from QDUser order by Uid asc");
            this.cmbLeader.DisplayMember = "UName";
            this.cmbLeader.ValueMember = "Uid";
            this.cmbLeader.DataSource = dt_qduser;

            this.cmbDeveloper.DisplayMember = "UName";
            this.cmbDeveloper.ValueMember = "Uid";
            this.cmbDeveloper.DataSource = dt_qduser.Copy();

            this.cmbTester.DisplayMember = "UName";
            this.cmbTester.ValueMember = "Uid";
            this.cmbTester.DataSource = dt_qduser.Copy();

            this.cmbTester.SelectedValue = "";
            this.cmbLeader.SelectedValue = "";
            this.cmbDeveloper.SelectedValue = "";
        }

        public override void ToolsBtnAdd_Click(object sender, EventArgs e)
        {
            //ControlHelper.SetChildReadonly(this.tabControl1.TabPages[0], false, readIgnoreControls);
            SetReadonly(false);
            this.tabControl1.SelectedIndex = 0;
            PageState = PageState.Append;
            this.QfCode.Text = "";
            this.QfName.Text = "";
            this.SerialNumber.Text = "";
            this.CreateDate.Text = "";
            this.cmbTester.SelectedValue = "";
            this.cmbLeader.SelectedValue = "";
            this.cmbDeveloper.SelectedValue = "";
        }

        protected override void ToolsBtnDelete_Click(object sender, EventArgs e)
        {
            DialogResult isOk = PromptHelper.PromptOkCancel("删除会把模块关联的程序一起删除，确定删除吗？");
            if (isOk == DialogResult.OK)
            {
                try
                {
                    var qfCode = this.QfCode.Text;
                    if (!string.IsNullOrEmpty(qfCode))
                    {
                        QDResources db = new QDResources();

                        string sql = @"delete from QDDataBase where QfCode='" + qfCode + "';";
                        db.ExecuteScalar(sql);
                        this.QfCode.Text = "";
                        this.QfName.Text = "";
                        this.CreateDate.Text = "";
                        this.SerialNumber.Text = "";
                        this.cmbTester.SelectedValue = "";
                        this.cmbLeader.SelectedValue = "";
                        this.cmbDeveloper.SelectedValue = "";
                        GridList_DataBind();
                        PromptHelper.Prompt("删除成功！");
                    }
                    else
                    {
                        PromptHelper.Prompt("请选择程序模块！");
                    }
                }
                catch (Exception ex)
                {
                    PromptHelper.Prompt(ex);
                }

            }
        }

        protected override void ToolsBtnDetail_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedCellCollection cells = this.grid_list.SelectedCells;
            if (cells.Count == 0)
            {
                PromptHelper.Prompt("请选择要查看的用户！");
            }
            else
            {
                string qfCode = this.grid_list.Rows[cells[0].RowIndex].Cells["ListQfCode"].Value.ToString();
                InitUIData(qfCode);
            }
        }

        protected override void ToolsBtnModify_Click(object sender, EventArgs e)
        {
            //ControlHelper.SetChildReadonly(this.tabControl1.TabPages[0], false, readIgnoreControls);
            SetReadonly(false);
            PageState = PageState.Modify;
        }

        protected override void ToolsBtnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                if (PageState == PageState.Append || PageState == PageState.Modify)
                {
                    string qfCode = this.QfCode.Text.Trim();
                    string qfName = this.QfName.Text.Trim();

                    using (QDResources db = new QDResources())
                    {
                        #region 保存表单主表
                        QDDataBase mod = null;
                        if (PageState == PageState.Append)
                        {
                            mod = new QDDataBase();
                            if (db.QDDataBase.Any(p => p.QfCode == qfCode))
                            {
                                throw new Exception("产品编号已经存在！");
                            }
                            else if (db.QDDataBase.Any(p => p.QfName == qfName))
                            {
                                throw new Exception("产品名称已经存在！");
                            }
                            else
                            {
                                mod.QfCode = qfCode;
                                mod.CreateDate = DateTime.Now;
                                db.QDDataBase.Add(mod);
                            }
                        }
                        else
                        {
                            if (!db.QDDataBase.Any(p => p.QfCode == qfCode))
                            {
                                throw new Exception("产品" + qfCode + "不存在或已经被删除，操作失败！");
                            }
                            else
                            {
                                mod = db.QDDataBase.FirstOrDefault(p => p.QfCode == qfCode);
                            }
                        }

                        mod.QfName = qfName;
                        mod.SerialNumber = this.SerialNumber.Text.Trim();
                        mod.DeveloperCode = this.cmbDeveloper.SelectedValue.ToString();
                        mod.LeaderCode = this.cmbLeader.SelectedValue.ToString();
                        mod.TesterCode = this.cmbTester.SelectedValue.ToString();

                        if (string.IsNullOrEmpty(mod.QfCode))
                        {
                            throw new Exception("产品编号不能为空！");
                        }
                        else if (string.IsNullOrEmpty(mod.QfName))
                        {
                            throw new Exception("产品名称不能为空！");
                        }
                        else if (string.IsNullOrEmpty(mod.SerialNumber))
                        {
                            throw new Exception("产品序列号不能为空！");
                        }

                        if (db.QDDataBase.Any(p => p.SerialNumber == mod.SerialNumber && p.QfCode != mod.QfCode))
                        {
                            throw new Exception("产品序列号 [" + mod.SerialNumber + "] 已经存在！");
                        }

                        #endregion
                        db.SaveChanges();
                    }
                    PromptHelper.Prompt("保存成功！");

                    //ControlHelper.SetChildReadonly(this.tabControl1.TabPages[0], true, readIgnoreControls);
                    SetReadonly(true);
                    PageState = PageState.Browse;

                    GridList_DataBind();
                    InitUIData(qfCode);
                }
            }
            catch (DbEntityValidationException ex)
            {
                GeneralTools.EFValidaPrompt(ex);
            }
            catch (Exception ex)
            {
                PromptHelper.Prompt(ex);
            }
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            GridList_DataBind();
            this.tabControl1.SelectedIndex = 1;
        }

        private void txtKey_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                toolStripButton6_Click(sender, e);
            }
        }

        private void GridList_DataBind()
        {
            QDResources db = new QDResources();
            string key = this.txtKey.Text.Trim().ToLower();
            //IList<QDDataBase> userList;
            DataTable userList;
            string sql = @"select [QfCode]
      ,[QfName]
      ,[SerialNumber]
      ,[CreateDate]
      , (select UName from QDUser where Uid = a.[DeveloperCode])[DeveloperCode]
      ,(select UName from QDUser where Uid = a.[LeaderCode])[LeaderCode]
      ,(select UName from QDUser where Uid = a.[TesterCode])[TesterCode]
                from QDDataBase a {0} Order By QfCode";
            if (string.IsNullOrEmpty(key))
            {
                //userList = db.QDDataBase.OrderBy(p => p.QfCode).ToList();
                userList = db.Query(string.Format(sql, ""));
            }
            else
            {
                //userList = db.QDDataBase.Where(p => p.QfCode.ToLower().Contains(key) || p.QfName.ToLower().Contains(key)).OrderBy(p => p.QfCode).ToList();
                userList = db.Query(string.Format(sql, "where QfCode like '%" + key + "%' or QfName like '%" + key + "%'"));
            }
            this.grid_list.DataSource = userList;
        }

        private void grid_list_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1 && e.ColumnIndex > -1)
            {
                string qfCode = this.grid_list.Rows[e.RowIndex].Cells["ListQfCode"].Value.ToString();
                InitUIData(qfCode);
            }
        }

        protected override void InitUIData(string qfCode)
        {
            bool isInit = true;

            if (PageState != PageState.Browse && PromptHelper.PromptOkCancel("当前数据未保存，是否放弃保存？") == DialogResult.Cancel)
            {
                isInit = false;
            }
            if (isInit)
            {
                QDResources db = new QDResources();
                QDDataBase mod = db.QDDataBase.First(p => p.QfCode == qfCode);

                this.QfCode.Text = mod.QfCode;
                this.QfName.Text = mod.QfName;
                this.SerialNumber.Text = mod.SerialNumber;
                this.CreateDate.Text = mod.CreateDate.ToString();
                this.cmbTester.SelectedValue = mod.TesterCode == null ? "" : mod.TesterCode;
                this.cmbLeader.SelectedValue = mod.LeaderCode == null ? "" : mod.LeaderCode;
                this.cmbDeveloper.SelectedValue = mod.DeveloperCode == null ? "" : mod.DeveloperCode;

                this.tabControl1.SelectedIndex = 0;

                PageState = PageState.Browse;
                //ControlHelper.SetChildReadonly(this.tabControl1.TabPages[0], false, readIgnoreControls);
                SetReadonly(true);
            }
            base.InitUIData(qfCode);
        }
        protected override void ToolsBtnPrevious_Click(object sender, EventArgs e)
        {
            QDDataBase ftMod = IsCurrentExists();
            if (ftMod != null)
            {
                QDResources dbConfig = new QDResources();
                QDDataBase mod = dbConfig.QDDataBase.Where(p => p.CreateDate < ftMod.CreateDate).OrderByDescending(p => p.CreateDate).FirstOrDefault();
                if (mod == null)
                {
                    PromptHelper.Prompt("已经是第一条数据了！");
                }
                else
                {
                    InitUIData(mod.QfCode);
                }
            }
        }

        protected override void ToolsBtnNext_Click(object sender, EventArgs e)
        {
            QDDataBase ftMod = IsCurrentExists();
            if (ftMod != null)
            {
                QDResources dbConfig = new QDResources();
                QDDataBase mod = dbConfig.QDDataBase.Where(p => p.CreateDate > ftMod.CreateDate).OrderBy(p => p.CreateDate).FirstOrDefault();
                if (mod == null)
                {
                    PromptHelper.Prompt("已经是最后一条数据了！");
                }
                else
                {
                    InitUIData(mod.QfCode);
                }
            }
        }

        private QDDataBase IsCurrentExists()
        {
            QDDataBase ftMod = null;
            string qfCode = this.QfCode.Text.Trim();
            if (string.IsNullOrEmpty(qfCode))
            {
                PromptHelper.Prompt("未加载任何用户信息！");
            }
            else
            {
                QDResources dbConfig = new QDResources();
                ftMod = dbConfig.QDDataBase.FirstOrDefault(p => p.QfCode == qfCode);

                if (ftMod == null)
                {
                    PromptHelper.Prompt("产品 [" + qfCode + "] 未保存或已经被删除！");
                }
            }

            return ftMod;
        }

        private void 复制单元格ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.grid_list.CopyFirstSelectedCellValue();
        }

        private void 复制所有选中单元格ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.grid_list.CopySelectedCellsValue();
        }
        private void SetReadonly(bool isReadonly)
        {
            this.QfCode.ReadOnly = isReadonly;
            this.QfName.ReadOnly = isReadonly;
            this.SerialNumber.ReadOnly = isReadonly;
            this.cmbTester.Enabled = !isReadonly;
            this.cmbLeader.Enabled = !isReadonly;
            this.cmbDeveloper.Enabled = !isReadonly;
            //this.CreateDate.ReadOnly = isReadonly;
        }
        private void Product_Shown(object sender, EventArgs e)
        {

            this.txtKey.Focus();
        }
    }
}
